package com.lhczf.lucenedb.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.Document;

import java.lang.reflect.Field;

@Slf4j
public class BeanFactory {
    private BeanFactory() {
    }

    public static Object getBean(Document document, Class beanClass) {
        Object object = null;
        try {
            object = beanClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("", e);
        }
        if (document == null) {
            return object;
        }
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            Object value = document.get(field.getName());
            field.setAccessible(true);
            String typeName = field.getGenericType().getTypeName();
            try {
                if ("long".equals(typeName)) {
                    field.set(object, Long.parseLong(String.valueOf(value)));
                } else if ("int".equals(typeName)) {
                    field.set(object, Integer.parseInt(String.valueOf(value)));
                } else if ("double".equals(typeName)) {
                    field.set(object, Double.parseDouble(String.valueOf(value)));
                } else {
                    field.set(object, value);
                }
            } catch (IllegalAccessException e) {
                log.error("", e);
            }
        }
        return object;
    }
}
